//
//  ChooseViewController.swift
//  Keyboard
//
//  Created by xinglian on 2022/12/20.
//

import UIKit
import ZLPhotoBrowser
enum sendType{
    case normal
    case photo
    case bin
}
enum ChooseViewControllerStyle {
    case chooseStyle
    case function
}
private var imgData = NSData()
let IMG_KEY = "IMG_KEY"
class ChooseViewController: BaseViewController {
    @IBOutlet var btn1: UIButton!
    @IBOutlet var btn2: UIButton!
    @IBOutlet var btn3: UIButton!
    @IBOutlet var tips: UILabel!
    var index = 0
    var array = Array<Any>()
    var type:sendType = .normal
    var style:ChooseViewControllerStyle = .chooseStyle
    var bin:Data?
    var speed : Int = Int(XKeyChain.get(speedKey)) ?? 1{
        didSet{
            XKeyChain.set("\(speed)", key: speedKey)
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    
    override func initUI() {
        let choose = style == .chooseStyle
        self.btn1.setTitle(choose ? LS("选择自定义") : LS("照片"), for: .normal)
        self.btn2.setTitle(choose ? LS("默认动画") : LS("拍照"), for: .normal)
        self.btn1.setImage(choose ? nil : UIImage(named:"相册"), for: .normal)
        self.btn2.setImage(choose ? nil : UIImage(named:"相机"), for: .normal)
        self.btn3.setTitle(LS("自定义速度"), for: .normal)
        self.btn3.isHidden = choose
        self.btn1.titleEdgeInsets = choose ? .zero : UIEdgeInsets(top:0, left:-130, bottom:0, right:0)
        self.btn1.imageEdgeInsets = choose ? .zero : UIEdgeInsets(top:0, left:0, bottom:0, right:-150)
        self.btn2.titleEdgeInsets = choose ? .zero : UIEdgeInsets(top:0, left:-130, bottom:0, right:0)
        self.btn2.imageEdgeInsets = choose ? .zero : UIEdgeInsets(top:0, left:0, bottom:0, right:-150)
        self.tips.text = LS("温馨提示\n更换单图和GIF图片尺寸分辨率均需大于320*172，无大小限制")
    }
    func gotoEdit(_ imgs:[UIImage]?=nil, _ block:(()->Void)?=nil){
        let vc = EditViewController()
        vc.speed = speed
        vc.imgs = imgs ?? [UIImage]()
        vc.block = { [weak self] speed in
            self?.speed = speed
            block?()
        }
        push(vc,true)
    }
    
    @IBAction func actionForBtn(_ sender: UIButton) {
        switch (sender.tag, style){
        case (201,.chooseStyle):///选择自定义
            let vc = ChooseViewController()
            vc.style = .function
            self.push(vc,true)
        case (201,.function):///照片
            KBTool.openAblum(9) {[weak self] datas,imgs   in
                CCHud.start(LS("处理数据中..."))
                if imgs.count > 1{///多张图片
                    self?.gotoEdit(imgs){
                        BleDataTool.share.setGIF(datas, 11 - (self?.speed ?? 0)) { data in
                            imgData = data as NSData
                        }
                    }
                }else{///单张图片
                    BleDataTool.share.setGIF(datas, 11 - (self?.speed ?? 0)) { data in
                        imgData = data as NSData
                    }
                }
            }
        case (202,.chooseStyle):///默认动画
            BleDataTool.share.defultLogo()
        case(202,.function):///相机
            KBTool.openCamera { datas in
                CCHud.start(LS("处理数据中..."))
                BleDataTool.share.setGIF(datas) { data in
                    imgData = data as NSData
                }
            }
        case (203,_):///自定义速度
            gotoEdit()
        case (204,_):///传bin文件
            let array = ["1.png","2.png","3.png","4.png"]
            var datas = [Data]()
            for name in array{
                let img = UIImage(named: name)
                let data = KBTool.redraw(img!, img!.size.width)
                datas.append(data)
            }
            BleDataTool.share.setGIF(datas) { data in
                imgData = data as NSData
            }
            return
            let size = imgData.count
            BleDataTool.share.setImgInfo(true,"\(size)")
        default:
            break
        }
    }
    
    /// bin文件拆分
    private func handleData()
    {
        self.index = 0
        self.array.removeAll()
        let data : NSData =  imgData
        
        let count =  data.length/4096 + (data.length%4096 > 0 ? 1 : 0)
        var length = 1024 * 4
        for i in 0 ..< count
        {
            let subData = NSMutableData()
            var tempData = NSData()
            var subArray = Array<NSMutableData>()
            length = (i == count - 1) ? data.length%4096 : length
            if i == 0
            {
                let totalLength = "\(data.length + 17)".toHex().fix(8, "0")
                ///command+key+索引 01+索引后面数据的字节长度+起始位置+结束位置+CRC+固定结尾
                ///自定义表盘和市场表盘开始和结束都是 0x00FFFFFF   16777215
                let firstData = "0805"+"01"+"0009"+"00FFFFFF"+"00FFFFFF"+"02"+"02FFFF"
                let header = String(format:"880000%@00%@", totalLength, firstData)
                subData.append(header.hexadecimal()!)
            }
            tempData = data.subdata(with: NSRange(location:i*4096, length:length)) as NSData
            subData.append(tempData as Data)
            
            //拆181小包
            let subDataCount = subData.count/181 + (subData.count%181 > 0 ? 1 : 0)
            var subDataLength = 181
            
            for j in 0 ..< subDataCount
            {
                subDataLength = (j == subDataCount - 1) ? subData.count%181 : subDataLength
                let data181 = subData.subdata(with:NSRange(location:j*181, length:subDataLength))
                subArray.append(KBTool.crc8Data(data181 as NSData) as! NSMutableData)
            }
            self.array.append(subArray)
        }
        ///3.10.3协议 擦除制定flash区域
        BleDataTool.share.clearFlash()
    }
    
    func send(){
        BleDataTool.share.sendImgData(self.array, self.index)
    }
}
//MARK: - 通知
extension ChooseViewController{
    override func addNotify() {
        if style == .chooseStyle{return}
        NotificationCenter.default.addObserver(self, selector: #selector(actionForBLE3114Response), name: BLE3114Response, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(actionForBLE3104Response), name: BLE3104Response, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(actionForBLE3106Response), name: BLE3106Response, object: nil)
    }
    
    @objc func actionForBLE3114Response(notify:Notification){
        switch notify.object as? String ?? ""{
        case "01":
            print("出入非法值")
        case "02":
            self.handleData()
            print("等待APP端发送表盘FLASH数据")
        case "03":
            print("设备已经有存储这个表盘，设备端调用并显示")
        case "04":
            print("设备存储空间不够，需要APP端调用3.11.5处理")
        case "05":
            print("其他高优先级数据在处理")
        default:
            break
        }
    }
    
    
    @objc func actionForBLE3104Response(notify:Notification){
        switch notify.object as? String ?? ""{
        case "01":
            print("不支持擦鞋flash数据")
        case "02":
            self.send()
            print("已经擦写FLASH数据   \(self)")
        default:
            break
        }
    }
    
    @objc func actionForBLE3106Response(notify:Notification){
        switch notify.object as? String ?? ""{
        case "01","03","04":
            let per = String(format:"%d%%", Int(CGFloat(self.index)/CGFloat(self.array.count)*100))
            CCHud.start(LS("发送数据中...")+per)
            BleDataTool.share.sendImgData(self.array, self.index)
            print("某个数据异常，忽略")
        case "02":
            self.index = self.array.count
            let per = String(format:"%d%%", Int(CGFloat(self.index)/CGFloat(self.array.count)*100))
            CCHud.start(LS("发送数据中...")+per, stopTime: 2)
            print("更新成功")
        case "05":
            self.index += 1
            let per = String(format:"%d%%", Int(CGFloat(self.index)/CGFloat(self.array.count)*100))
            CCHud.start(LS("发送数据中...")+per)
            BleDataTool.share.sendImgData(self.array, self.index)
            MyPrint("=====写入\(self.index)/\(self.array.count)数据")
        case "06":
            CCHud.start(LS("异常退出，包含超时"), stopTime: 2){
                self.navigationController?.popViewController(animated: true)
            }
            print("异常退出，包含超时")
        default:
            break
        }
    }
}


